package com.foreknow.springioc;

import com.foreknow.bean.Admin;
import com.foreknow.service.impl.AdminServiceImpl;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ClassPathXmlApplicationContext implements BeanFactory {
    private Map<String, Object> beans = new HashMap<String, Object>();

    //解析xml文件
    public ClassPathXmlApplicationContext() throws JDOMException, IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //1.创建 SAXBuilder builder = new SAXBuilder();对象
        SAXBuilder builder = new SAXBuilder();
        //2.构建Document文档
        Document document = builder.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml"));
        //3.获取根节点
        Element element = document.getRootElement();
        //4.获取子节点
        List<Element> list = element.getChildren();
        //5.遍历
        for (int i = 0; i < list.size(); i++) {
            Element elm = list.get(i);
            //获取id和class
            String id = elm.getAttributeValue("id");
            String clazz = elm.getAttributeValue("class");
            //将clazz转换为Object对象
            Object o = Class.forName(clazz).newInstance();
            //将获取到的id和o对象保存到Map集合中
            beans.put(id, o);
            //获取到子元素<property name="adminDao" bean="u"></property>
            for (Element property : elm.getChildren()) {
                String name = property.getAttributeValue("name");
                String bean = property.getAttributeValue("bean");
                Object beanObject = beans.get(bean);//AdminDaoImpl对象
                //调用public void setAdminDao(AdminDao adminDao) {
                //        this.adminDao = adminDao;
                //    }方法进行初始化
                //拼接方法
                String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
//                System.out.println(methodName);
                Method method = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces());//(,admindao)
                //调用方法
                method.invoke(o, beanObject);//(adminserviceimpl,admindaoimpl)
            }
//            System.out.println(id+"-----"+clazz);

        }

    }

    @Override
    public Object getBean(String id) {
        return null;
    }

    public static void main(String[] args) throws JDOMException, IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext();
        AdminServiceImpl service = (AdminServiceImpl) beanFactory.getBean("adminService");
        service.add(new Admin());
    }
}
